from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy # type: ignore
from flask_login import LoginManager # type: ignore
from flask_migrate import Migrate # type: ignore
from api.config import Config
from api.logger import setup_logger

# 创建扩展实例
db = SQLAlchemy()
login_manager = LoginManager()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 初始化扩展
    CORS(app)
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)
    
    # 设置日志
    setup_logger(app)
    
    # 注册路由蓝图
    from api.routes import main_bp, auth_bp, collection_bp, browse_bp
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp)
    app.register_blueprint(collection_bp)
    app.register_blueprint(browse_bp)
    
    return app

# 用户加载回调
@login_manager.user_loader
def load_user(id):
    from api.models import User
    return User.query.get(int(id)) 